<?php


namespace app\engine\controller;


use cmf\controller\HomeBaseController;
use think\Db;
use think\db\Where;

class ConstController extends HomeBaseController
{
    public function index()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $name = Db::name('engine')->where(['id'=>$id])->value('name');
        $res = Db::name('constr')->where(['eid' => $id])->group('type')->field('eid,type')->select()->toArray();
        $this->assign('name',$name);
        $this->assign('res', $res);
        $this->assign('id', $id);
        return $this->fetch();
    }

    public function add()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2 || $role == 4 || $role == 3){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $id = $data['id'];
        $type = $data['type'];
        $this->assign('id', $id);
        $this->assign('type', $type);
        if ($type == 2) {
            $people = Db::name('staff')->field('id,name')->select()->toArray();
            $sye = Db::name('staff')->field('id,position')->select()->toArray();
            $this->assign('people', $people);
            $this->assign('sye', $sye);
            return $this->fetch();
        } elseif ($type == 1) {
            $people = Db::name('leader')->where(['eid' => $id])->field('id,name')->select()->toArray();
            $sye = Db::name('leader')->where(['eid' => $id])->field('id,type')->select()->toArray();
            $this->assign('people', $people);
            $this->assign('sye', $sye);
            return $this->fetch('adds');
        } elseif ($type == 3) {
            $people = Db::name('leader')->where(['eid' => $id])->field('id,name')->select()->toArray();
            $sye = Db::name('leader')->where(['eid' => $id])->field('id,type')->select()->toArray();
            $this->assign('people', $people);
            $this->assign('sye', $sye);
            return $this->fetch('addps');
        } elseif ($type == 4) {
            $people = Db::name('staff')->field('id,name')->select()->toArray();
            $sye = Db::name('leader')->where(['eid' => $id])->field('id,type,name')->select()->toArray();
            $this->assign('people', $people);
            $this->assign('sye', $sye);
            return $this->fetch('addpo');
        } elseif ($type == 5) {
            $people = Db::name('staff')->field('id,name')->select()->toArray();
            $sye = Db::name('leader')->where(['eid' => $id])->field('id,type,name')->select()->toArray();
            $this->assign('people', $people);
            $this->assign('sye', $sye);
            return $this->fetch('addpcp');
        }
    }

    public function doadd()
    {
        $data = $this->request->param();
        if (empty($data['leader']) || empty($data['leaType'])) {
            $this->error('请检查关键信息是否填写完整');
        }
        if ($data['type'] == 1 || $data['type'] == 2 || $data['type'] == 3) {
            $data['uid'] = cmf_get_current_admin_id();
        }else{
            $files = $this->request->file('img');
            $kps = [];
            if ($files) {
                foreach ($files as $k => $file) {
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
                    if ($info) {
                        $kps[$k] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
                    } else {
                        $this->error($file->getError());
                    }
                }
                $data['img'] = implode(',', $kps);
            }
        }
        $res = Db::name('constr')->insert($data);
        if (!$res) {
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    public function see()
    {
        $role = Db::name('role_user')->where(['user_id' => cmf_get_current_admin_id()])->value('role_id');
        $user_id = cmf_get_current_admin_id();
        $data = $this->request->param();
        $res = Db::name('constr')->where($data)->order('time desc')->select()->toArray();
        $kp = $res;
        foreach ($res as $k => &$v) {
            if ($v['type'] == 2) {
                $v['lname'] = Db::name('staff')->where(['id' => $v['leader']])->value('name');
                $v['ltype'] = Db::name('staff')->where(['id' => $v['leader']])->value('position');
                $v['admin_name'] = Db::name('user')->where(['id' => $v['editId']])->value('user_login');

                $all = Db::name('constr')->where($data)->where(['del' => 1])->group('leader')->field('leader')->select()->toArray();
                foreach ($all as $k => &$c) {
                    $c['uName'] = Db::name('staff')->where(['id' => $c['leader']])->value('name');
                    $c['numbers'] = Db::name('constr')->where(['leader' => $c['leader'], 'type' => $v['type'], 'del' => 1,'eid'=> $data['eid']])->sum('nums');
                }
            } else {
                $v['lname'] = Db::name('leader')->where(['id' => $v['leader'], 'eid' => $v['eid']])->value('name');
                $v['ltype'] = Db::name('leader')->where(['id' => $v['leader'], 'eid' => $v['eid']])->value('type');
                $v['admin_name'] = Db::name('user')->where(['id' => $v['editId']])->value('user_login');

                $all = Db::name('constr')->where($data)->where(['del' => 1])->group('leader')->field('leader')->select()->toArray();
                foreach ($all as $k => &$c) {
                    $c['uName'] = Db::name('leader')->where(['id' => $c['leader']])->value('name');
                    $c['numbers'] = Db::name('constr')->where(['leader' => $c['leader'], 'type' => $v['type'], 'del' => 1])->sum('nums');
                }
            }
            $v['uname'] = Db::name('user')->where(['id' => $v['uid']])->value('user_login');
        }
        $this->assign('all', $all);
        $this->assign('userId', $user_id);
        $this->assign('id', $data['eid']);
        $this->assign('res', $res);
        $this->assign('role',$role);
        return $this->fetch();
    }

    public function look()
    {
        $data = $this->request->param();
        $res = Db::name('constr')->where($data)->find();
        if ($res['type'] == 1) {
            $res ['lname'] = Db::name('leader')->where(['id' => $res['leader']])->value('name');
            $res['ltype'] = Db::name('leader')->where(['id' => $res['leader']])->value('type');
            $this->assign('res', $res);
            return $this->fetch();
        } elseif ($res['type'] == 2) {
            $res ['lname'] = Db::name('staff')->where(['id' => $res['leader']])->value('name');
            $res['ltype'] = Db::name('staff')->where(['id' => $res['leaType']])->value('position');
            $this->assign('res', $res);
            return $this->fetch('looks');
        } elseif ($res['type'] == 3) {
            $res ['lname'] = Db::name('leader')->where(['id' => $res['leader']])->value('name');
            $res['ltype'] = Db::name('leader')->where(['id' => $res['leader']])->value('type');
            $this->assign('res', $res);
            return $this->fetch('lookes');
        } elseif ($res['type'] == 4) {
            $res['uname'] = Db::name('staff')->where(['id' => $res['uid']])->value('name');
            $res ['lname'] = Db::name('leader')->where(['id' => $res['leader']])->value('name');
            $res['ltype'] = Db::name('leader')->where(['id' => $res['leader']])->value('type');
            $res['img'] = explode(',',$res['img']);
            foreach ($res['img'] as $k => &$v) {
                $v = 'http://' .$_SERVER['SERVER_NAME']. $v;
            }
            $this->assign('res', $res);
            return $this->fetch('lookps');
        } elseif ($res['type'] == 5) {
            $res['uname'] = Db::name('staff')->where(['id' => $res['uid']])->value('name');
            $res ['lname'] = Db::name('leader')->where(['id' => $res['leader']])->value('name');
            $res['ltype'] = Db::name('leader')->where(['id' => $res['leader']])->value('type');
            $res['img'] = explode(',',$res['img']);
            foreach ($res['img'] as $k => &$v) {
                $v = 'http://' .$_SERVER['SERVER_NAME']. $v;
            }
            $this->assign('res', $res);
            return $this->fetch('lookps');
        }
    }

    public function loks()
    {
        $data = $this->request->param();
        $res = Db::name('constr')->where($data)->select()->toArray();
        foreach ($res as $k => &$v) {
            $v['sname'] = Db::name('staff')->where(['id' => $v['uid']])->value('name');
            $v['lname'] = Db::name('leader')->where(['id' => $v['leader']])->value('name');
            $v['ltype'] = Db::name('leader')->where(['id' => $v['leaType']])->value('type');
            $v['admin_name'] = Db::name('user')->where(['id' => $v['editId']])->value('user_login');
        }
        $this->assign('res', $res);
        $this->assign('id', $data['eid']);
        return $this->fetch();
    }

    public function doedit()
    {
        $data = $this->request->param();
        $files = request()->file('img');
        $id = $data['id'];
        unset($data['id']);
        $check = Db::name('constr')->where(['id' => $id])->find();

        // 处理要删除的图片
        $removeImg = isset($data['remove_img']) ? $data['remove_img'] : [];
        unset($data['remove_img']);

        // 处理保留的旧图片
        $oldImg = isset($data['old_img']) ? $data['old_img'] : [];
        unset($data['old_img']);

        // 处理凭据图片
        if (!is_null($files) || !empty($removeImg)) {
            $kps = [];
            // 如果有旧图片，先添加到数组中
            if (!empty($oldImg)) {
                // 处理旧图片，去除域名只保留路径
                foreach ($oldImg as $img) {
                    if (!empty($img)) {
                        // 如果图片路径包含域名，只保留路径部分
                        if (strpos($img, 'http://') === 0 || strpos($img, 'https://') === 0) {
                            $parsedUrl = parse_url($img);
                            $kps[] = $parsedUrl['path'];
                        } else {
                            $kps[] = $img;
                        }
                    }
                }
            } else if (!empty($check['img']) && empty($removeImg)) {
                // 如果没有指定旧图片但数据库中有图片且没有要删除的图片，则使用数据库中的图片
                $imgArray = explode(',', $check['img']);
                foreach ($imgArray as $img) {
                    if (!empty($img)) {
                        $kps[] = $img;
                    }
                }
            }

            // 处理新上传的图片
            if (!is_null($files)) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($files as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $kps[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
            }

            $data['img'] = implode(',', $kps);
        }

        // 处理是否作废
        if (empty($data['del'])) {
            $this->error('请选择是否作废 一旦作废不可恢复');
        }
        
        // 记录编辑人ID
        $data['editId'] = cmf_get_current_admin_id();
        
        // 更新数据
        $res = Db::name('constr')->where(['id' => $id])->update($data);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    public function del()
    {
        $data = $this->request->param();
        $res = Db::name('constr')->where(['id' => $data['id']])->delete();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

}